<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import {
    DatalibGroupVariety,
    DatalibVarietyIndexGroupTree,
    // CalculationGroupTree,
  } from '@/api/datlib/variety'
  import { FutureVarietyRealTimeQuotation } from '@/api/futures/quotation'
  import { ElMessageBox } from 'element-plus';

  const appRouter = useRouter()

  const DATAVIEWNAME = 'dataview'
  // 页面名称
  const currViewName = ref(null)

  const treeProps = {
    label: 'name',
    isLeaf: 'leaf'
  }


  // 品种数据
  const varietyGroups = reactive({
    data: []
  })

  // 当前显示的品种
  const currentVariety = reactive({
    isExchange: false,
    name: '-',
    code: '-',
    curClassName: 'quote-box',
    textColor: '',
    curQuote: '',
    change: '-',
    curQuoteChange: '-',
    curQuoteChangeRatio: '-',
    curTime: '',
    curUnit: '',
    datalibGroups: [],
    expandGroupKeys: [],
    breadcrumbs: [],
    calculationGroups: [],
    reportGroups: []
  })

  // 当前显示的指标列表
  // const currentIndexes = reactive({
  //   showList: [],
  //   hiddenList: [],
  //   isMore: false,
  //   showMore: false
  // })


  // ---------- 工具函数
  // 获取组别
  const getVarietyGroup = (gKey) => {
    let groupItem = null
    for (let i=0; i<varietyGroups.data.length;i++) {
      if (varietyGroups.data[i].key == gKey) {
        groupItem = varietyGroups.data[i]
        break
      }
    }
    return groupItem
  }

  // ---------- 功能函数

  // 鼠标进入分组
  const mouseEnterGroup = (gKey) => {
    varietyGroups.data.forEach((g) => {
      g.subShow = g.key === gKey ? true : false
    })
  }

  // 鼠标离开分组
  const mouseLeaveGroup = () => {
    mouseEnterGroup('0') // 鼠标向上离开菜单，隐藏子菜单
  } 

  // 点击某个品种
  const toShowVarietyDatalib = (gKey, vItem) => {
    mouseEnterGroup(gKey + 'close')
    if (!vItem.access) {
      ElMessageBox.alert(`您还没有【${vItem.name}】品种的数据库权限，请联系客服开通...`)
      return
    }
    let g = getVarietyGroup(gKey)
    currentVariety.breadcrumbs = []
    currentVariety.breadcrumbs.push({ key: g.key, name: g.name })
    currentVariety.breadcrumbs.push({ key: vItem.code, name: vItem.name })
    currentVariety.isExchange = vItem.is_exchange
    currentVariety.name = vItem.name
    currentVariety.code = vItem.code
    currentVariety.curUnit = vItem.price_unit
    // 1. 请求指标分组,parent=0
    DatalibVarietyIndexGroupTree(vItem.code).then((res) => {
      // console.log(res)
      const groups = res.data.data
      currentVariety.datalibGroups = groups
      const firstGroup = getFirstGroup(groups)
      if (firstGroup) {
        toClickGroupTree(firstGroup)  // 点击第一分组下的最内部分组
      }
      // 设置默认展开的节点
      const defaultExpands = []
      for (let i=0; i < currentVariety.datalibGroups.length; i++) {
        defaultExpands.push(currentVariety.datalibGroups[i].id)
      }
      // console.log(defaultExpands)
      currentVariety.expandGroupKeys = defaultExpands

      // if (groups.length > 0) {
      //   toClickGroupTree(groups[0])  // 初始点击获取分组下的指标
      // } else {  // 若没有分组设定需清空指标
      //   // 后端不应该开放没有分组的品种
      // }
      // console.log(groups)
    })

    // 2. 请求计算公式分组,parent=0
    // CalculationGroupTree(vItem.code).then((res) => {
    //   const calculGroups = res.data.data
    //   currentVariety.calculationGroups = calculGroups
    // })
    // 3 市场研报类别分组
    // currentVariety.reportGroups = [
    //   { name: '日报', key: 'DAILY', },
    //   { name: '周报', key: 'WEEKLY',},
    //   { name: '月报', key: 'MONTHLY',},
    //   { name: '年报', key: 'ANNUAL',},
    // ]

    // 获取默认显示的指标数据(如果当前没有显示数据图形)
    

    if (!currentVariety.isExchange) {
      currentVariety.curQuote = '-'
      currentVariety.curQuoteChange = '-'
      currentVariety.curQuoteChangeRatio = '-'
      currentVariety.curTime = '-'
      return
    }

    // 3. 请求实时行情
    FutureVarietyRealTimeQuotation(vItem.code).then((res) => {
      const data = res.data.data
      currentVariety.curQuote = data.price
      currentVariety.change = data.change
      currentVariety.curQuoteChange = '' + data.change
      currentVariety.curQuoteChangeRatio = data.change_ratio + '%'
      currentVariety.curTime = data.quote_time
      if (data.change > 0) {
        currentVariety.curQuoteChange = '+' + data.change
        currentVariety.curClassName = 'quote-box bgred'
        currentVariety.textColor = 'red'
      }
      if (data.change < 0) {
        currentVariety.curClassName = 'quote-box bggreen'
        currentVariety.textColor = 'green'
      }
    })
  }


  // 懒加载指标分组
  // const lazyLoadIndexGroup = (nodeItem, resolve) => {
  //   const nodeData = nodeItem.data
  //   if (!nodeData.variety) return
  //   DatalibVarietyIndexGroup(nodeData.variety, nodeData.id).then((res) => {
  //     const groups = res.data.data
  //     return resolve(groups)
  //   })
  // }

  // 懒加载计算公式分组
  // const lazyLoadCalculationGroups = (nodeItem, resolve) => {
  //   const nodeData = nodeItem.data
  //   if (!nodeData.variety) return
  //   CalculationGroup(nodeData.variety, nodeData.id).then((res) => {
  //     const calculGroups = res.data.data
  //     return resolve(calculGroups)
  //   })
  // }

  // 懒加载报告列表
  // const lazyLoadGroupReports = (nodeItem, resolve) => {
  //   const nodeData = nodeItem.data
  //   if (nodeData.id) {
  //     return resolve([]) // 此时是报告，不能再次被懒加载
  //   }
  //   const curVen = currentVariety.code
  //   PaginatorPeriodReport(1, 10, nodeData.key, curVen).then((res) => {
  //     // console.log(res)
  //     const reportList = res.data.rows.map((item) => {
  //       item.name = item.title
  //       item.leaf = true
  //       return item
  //     })
  //     return resolve(reportList)
  //   })
  // }

  // 点击数据库分组节点
  const toClickGroupTree = (nodeItem) => {
    const breadLength = currentVariety.breadcrumbs.length
    if (breadLength === 2) {
      currentVariety.breadcrumbs.push({ key: nodeItem.id, name: nodeItem.name })
    } else {
      currentVariety.breadcrumbs.splice(breadLength - 1, 1, { key: nodeItem.id, name: nodeItem.name })
    }
    // 跳转路由
    appRouter.replace({
      path: '/datalib/dataview',
      name: 'datalibDataView',
      query: {igid: nodeItem.id, vcode: nodeItem.vcode}
    }).then(() => {
      // console.log('跳转数据库路由')
      currViewName.value = DATAVIEWNAME
    })
  }

  // 点击计算公式分组节点
  // const toClickCalculGroup = (nodeItem) => {
  //   // console.log(nodeItem)
  //   const breadLength = currentVariety.breadcrumbs.length
  //   if (breadLength === 2) {
  //     currentVariety.breadcrumbs.push({ key: nodeItem.id, name: nodeItem.name })
  //   } else {
  //     currentVariety.breadcrumbs.splice(breadLength - 1, 1, { key: nodeItem.id, name: nodeItem.name })
  //   }
  //   // 跳转路由
  //   appRouter.replace({
  //     path: '/datalib/datacalculate',
  //     name: 'datalibcalculateView',
  //     query: {cgid: nodeItem.id}
  //   }).then(() => {
  //     console.log('跳转计算路由')
  //     currViewName.value = DATAVIEWNAME
  //   })
  // }

  // 点击市场研报的节点(即请求一个报告文件)
  // const toClickReportGroup = (nodeItem) => {
  //   // console.log(nodeItem)
  //   if (!nodeItem.id) {
  //     return
  //   }
  //   // 跳转路由
  //   appRouter.replace({
  //     path: '/datalib/datareport',
  //     name: 'datalibReportView',
  //     query: {rfid: nodeItem.id}
  //   }).then(() => {
  //     console.log('跳转报告路由')
  //     currViewName.value = DATAVIEWNAME
  //   })
  // }

  // 取得组内第一个没有children的分组
  const getFirstGroup = (groupList) => {
    for (let i=0; i < groupList.length; i++) {
      const childrenList = groupList[i].children
      if (childrenList && childrenList.length > 0) {
        return getFirstGroup(childrenList)
      } else {
        return groupList[i]
      }
    }
  }

  // 页面初始加载数据初始化
  const initPageMounted = () => {
    // 1 请求品种分组和品种
    DatalibGroupVariety().then((res) => {
      varietyGroups.data = res.data.data.map((item) => {
        item.subShow = false
        return item
      })
      // 2请求第一个品种行情和第一层分组
      let firstVariety = null
      let inGroup = null
      for (let i=0;i<varietyGroups.data.length;i++) {
        let groupObj = varietyGroups.data[i]
        for (let j=0;j<groupObj.varieties.length;j++) {
          if (groupObj.varieties[j].access) {// 第一个有权限的品种
            firstVariety = groupObj.varieties[j]
            break
          }
        }
        if (firstVariety) {
          inGroup = groupObj
          break
        }
      }
      // console.log(firstVariety)
      // 点击第一个品种
      if (firstVariety){
        toShowVarietyDatalib(inGroup.key, firstVariety)
      }
    })
  }

  // onMounted生命周期钩子
  onMounted(() => {
    initPageMounted()
  })
</script>
<template>
  <div class="page-container">
    <!-- 品种分组 -->
    <div class="variety-group">
      <div
        v-for="group in varietyGroups.data"
        :key="group.key"
        class="g-item"
        @mouseenter="mouseEnterGroup(group.key)"
        @mouseleave="mouseLeaveGroup()"
      >
        <span class="g-name">{{ group.name }}</span>
        <div :class="group.subShow ? 'group-sub sub-show':'group-sub'">
          <div class="v-box">
            <div
              v-for="v in group.varieties"
              :key="v.code"
              :class="v.access ? 'v-item' : 'v-item no-access' "
              @click="toShowVarietyDatalib(group.key, v)"
            >{{ v.name }}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 内容 -->
    <div class="detail-box">
      <div class="left-pane">
        <el-scrollbar>
          <div :class="currentVariety.textColor">
            <div class="v-name"> {{ currentVariety.name }}</div>
            <div class="v-quote">{{ currentVariety.curQuote }}</div>
            <div :class="currentVariety.curClassName">
              <div>
                <span v-if="currentVariety.change > 0"><el-icon><Top /></el-icon></span>
                <span v-if="currentVariety.change < 0"><el-icon><Bottom /></el-icon></span>
                <span>{{ currentVariety.curQuoteChange }}</span>
              </div>
              <div>{{ currentVariety.curQuoteChangeRatio }}</div>
            </div>
          </div>
          <div class="quote-unit">
            <div>{{ currentVariety.curUnit }}</div>
            <div>{{ currentVariety.curTime }}</div>
          </div>
          <!-- 数据库 -->
          <div class="node-label">数据库</div>
          <div>
            <el-tree
              empty-text="暂无数据"
              node-key="id"
              :data="currentVariety.datalibGroups"
              :props="treeProps"
              :default-expanded-keys="currentVariety.expandGroupKeys"
              @node-click="toClickGroupTree"
            />
          </div>
          <!-- 市场研报 -->
          <!-- <div class="node-label">市场研报</div>
          <div>
            <el-tree
              lazy
              :props="treeProps"
              :data=currentVariety.reportGroups
              :load="lazyLoadGroupReports"
              @node-click="toClickReportGroup"
            />
          </div> -->
          <!-- 计算工具 -->
          <!-- <div class="node-label">计算平台</div>
          <div>
            <el-tree
              empty-text="无相关计算"
              :data="currentVariety.calculationGroups"
              :props="treeProps"
              @node-click="toClickCalculGroup"
            />
          </div> -->
        </el-scrollbar>
      </div>
      <div class="right-pane">
        <!-- 面包屑 -->
        <div class="breadcrumb">
          <el-breadcrumb separator-icon="ArrowRight">
            <el-breadcrumb-item
              v-for="(b, index) in currentVariety.breadcrumbs" 
              :key="index"
              class="breaditem"
            >{{ b.name }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <!-- 路由 -->
        <div>
          <RouterView />
        </div> 
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
  @keyframes showBox {
    0% {height: 0;} 100% {height: 130px;}
  }
  .page-container {
    // background: #efefef;
    .bgred {
      color: #d94532;
      background-color: rgba(202, 79, 60, 0.05) !important;
    }
    .bggreen {
      color: #5a923b;
      background-color: rgba(90, 146, 59, 0.05) !important;
    }
    .red {
      color: #d94532;
    }
    .green {
      color: #5a923b;
    }
    .variety-group {
      line-height: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      background-color: #eee;
      .g-item{
        position: relative;
        .g-name {
          margin-left: 10px;
          font-size: 15px;
          cursor: pointer;
          &:hover {
            color: #ea5404;
          }
        }
      }
      .group-sub {
        position: absolute;
        left: 10px;
        display: none;
        background-color: #eee;
        width: 500px;
        height: 130px;
        padding: 4px 8px;
        border: 1px solid #aaa;
        z-index: 9;
        .v-box {
          display: flex;
          flex-wrap: wrap;
          .v-item {
            width: 70px;
            height: 26px;
            text-align: left;
            line-height: 26px;
            font-size: 15px;
            padding: 0 4px;
            color: #023b8f;
            cursor: pointer;
            &:hover {
              color: #ea5404;
              text-decoration: underline;
            }
          }
          .no-access {
            color: #444;
            &:hover {
              color: #333;
              text-decoration: underline;
            }
          }
        }
        
      }
      .sub-show {
        display: block;
        animation: 500ms showBox;
      }
    }
    .detail-box {
      display: flex;
      .left-pane {
        background-color:  #fff;
        border: 1px solid #eeeeee;
        border-top: 0;
        min-width: 260px;
        width: 260px;
        min-height: calc(100vh - 70px);
        height: calc(100vh - 70px);
        .v-name {
          font-size: 19px;
          font-weight: 600;
          padding: 4px 0;
          text-align: center;
          margin-top: 8px;
        }
        .v-quote {
          font-size: 15px;
          text-align: center;
          line-height: 26px;
          height: 26px;
          margin-top: 8px;
        }
        .quote-box {
          margin-top: 8px;
          text-align: center;
          font-size: 14px;
          line-height: 26px;
          // background-color: #f5f7fa;
          background-color: rgba(202, 79, 60, 0.05);
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 30px;
          
        }
        .v-quote-change {
          display: flex;
          align-items: center;
          vertical-align: middle;
        }
      
        .quote-unit {
          margin-top: 8px;
          display: flex;
          justify-content: space-between;
          line-height: 26px;
          height: 26px;
          font-size: 11px;
          padding: 0 10px;
          color: #666;
        }
        .node-label {
          padding: 10px;
          font-size: 15px;
          font-weight: 600;
          margin-top: 16px;
        }
      }
      .right-pane {
        width: 1138px;
        background-color: #fff;
        border-right: 1px solid #eeeeee;
        width: 1138px;  // 1400 - 260 -2(left-pane的border)
        max-width: 1138px;
        height: calc(100vh - 68px);
        .breadcrumb {
          padding-left: 10px;
          .breaditem {
            height: 28px;
            line-height: 28px;
          }
        }
      }
    }
  }
  
</style>